package cn.simonfish.carrier.controller.api;

import cn.simonfish.carrier.common.Dict;
import cn.simonfish.carrier.common.Result;
import cn.simonfish.carrier.common.contsants.OrderStatus;
import cn.simonfish.carrier.controller.BaseController;
import cn.simonfish.carrier.kit.NumberKit;
import cn.simonfish.carrier.kit.SerialNumberKit;
import cn.simonfish.carrier.model.SysOrder;
import cn.simonfish.carrier.model.SysOrderItem;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.Date;
import java.util.Map;

/**
 * Created by simon on 2017/9/19.
 */
public class OrderApi extends BaseController {
    @Before(Tx.class)
    public void create(){
        String json = HttpKit.readData(getRequest());
        JSONObject jsonObject = JSON.parseObject(json);
        JSONArray itemArray = jsonObject.getJSONArray("sites");
        Map combo = Dict.getByFilter("combo","code",jsonObject.getString("combo"));
        String orderno = SerialNumberKit.generate("D");
        Double price = NumberKit.toDouble( combo.get("price") );
        int day = NumberKit.toInt( combo.get("day") );

        SysOrder order = new SysOrder();
        order.set("order_no",orderno);
        order.set("price",price);
        order.set("day", day );
        order.set("amount",price * itemArray.size());
        order.set("combo",combo.get("name"));
        order.set("status", OrderStatus.CREATED);
        initUserInfo(order);
        order.save();

        //保存子表内容
        for (int i = 0; i < itemArray.size(); i++) {
            String site = itemArray.getString(i);
            SysOrderItem item = new SysOrderItem();
            item.set("order_id",order.get("id"));
            item.set("order_no",order.get("order_no"));
            item.set("user_id",order.get("user_id"));
            item.set("user_phone",order.get("user_phone"));
            item.set("site1",site);
//            item.set("site2",itemObj.getString("site2"));
            item.set("price",price);
            item.set("day",day);
            item.set("create_time",new Date());
            item.save();
        }


        combo.put("amount", price * itemArray.size());


//        setAttr("order",order);
//        renderFreeMarker("template/order/pay.html");
        Result result = new Result(true);
        result.setData(order.getInt("id"));
        renderJson(result);
    }
}
